package com.ams.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ams.entity.User;
import com.ams.util.Constants;

public class PermiFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)arg0;
		HttpServletResponse res=(HttpServletResponse)arg1;
		HttpSession session=req.getSession();
		User user=(User)session.getAttribute(Constants.USER_KEY);
		String requestUri=req.getRequestURI();
		String reqeuestUrl=req.getRequestURL().toString();
		String refereAddress=req.getHeader("referer");
		
		//TODO:
		System.out.println("========================PermiFilter===========================");
		System.out.println("user=="+user);
		System.out.println("req.getHeader('referer')=="+req.getHeader("referer"));
		System.out.println("requestUrl=="+requestUri);
		System.out.println("requestURL=="+reqeuestUrl);
		System.out.println("==============================================================");
		
        if(user==null){
        	
			if(!(refereAddress!=null && refereAddress.endsWith("login.jsp"))){
				if(!requestUri.endsWith("login.jsp")){
					gotoLoginPage(req,res,session);
				}
				
			}
		}else{
			if(refereAddress==null ){
				
				if(!requestUri.endsWith("login.jsp")){
					String tip="请在资产管理系统的功能区进行合法操作,如果您还没有登录或者已经关闭了资产管理系统主页面，请重新登录！";
					req.setAttribute(Constants.MESSAGE, tip);
					req.setAttribute(Constants.TITLE_KEY,"非法操作");
					req.getRequestDispatcher("/error.jsp").forward(req, res);
					//res.sendRedirect("/error.jsp?message="+tip);
					return;
				}else{
					if(!session.isNew()){
						session.invalidate();
					}
				}
				
			}
		}
			
		chain.doFilter(req, res);
	}

	public void init(FilterConfig arg0) throws ServletException {

	}
	
	private void gotoLoginPage(HttpServletRequest req,HttpServletResponse res,HttpSession session)throws IOException{
		
		String path = req.getScheme() + "://" + req.getServerName() + ":"
				+ req.getServerPort() + req.getContextPath() + "/";
		//System.out.println("-====="+path);
		if(!session.isNew()){
			session.invalidate();   //Log off the current user 
		}
		
		PrintWriter out = res.getWriter();
		String script="<script>alert('您长时间没有操作，请重新登录');window.parent.location.href='" + path + "login.jsp"
		+ "';</script>";
		out.print(script);//Jump to login page 
		out.flush();
		out.close();
	}

}
